package com.woniuxy.exam.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.woniuxy.commons.entity.SingleChoice;
import com.woniuxy.exam.service.SingleChoiceService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zouyang
 * @date 2020/7/21 - 16:00
 */
public class SCListener extends AnalysisEventListener<SingleChoice> {

    private static final int BATCH_COUNT = 20;
    List<SingleChoice> list = new ArrayList<>();

    private SingleChoiceService singleChoiceService;
    public SCListener(SingleChoiceService singleChoiceService){
        this.singleChoiceService = singleChoiceService;
    }
    @Override
    public void invoke(SingleChoice singleChoice, AnalysisContext context) {
        list.add(singleChoice);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if(list==null){
            return;
        }
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    private void saveData() {
        singleChoiceService.insertList(list);
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if(list.isEmpty()==false){
            saveData();
        }
        list.clear();
        list=null;
    }
}
